/**
* 版权声明：厦门睿商网络科技有限公司 版权所有 违者必究
* 日    期：2020-02-17
*/
package com.rzico.basics.controller.admin;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.rzico.annotation.Log;
import com.rzico.base.BaseController;
import com.rzico.base.CommResult;
import com.rzico.basics.entity.Enterprise;
import com.rzico.basics.entity.Shop;
import com.rzico.basics.service.EnterpriseService;
import com.rzico.basics.service.ShopService;
import com.rzico.core.entity.SysEmployee;
import com.rzico.core.entity.SysOffice;
import com.rzico.core.entity.SysUser;
import com.rzico.core.service.SysEmployeeService;
import com.rzico.core.service.SysOfficeService;
import com.rzico.core.service.SysUserService;
import com.rzico.entity.PageResult;
import com.rzico.entity.Pageable;
import com.rzico.util.AreaUtils;
import com.rzico.util.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 店铺/仓库控制层
 *
 * @author Rzico Boot
 * @version 1.0
 * @date 2020-02-17
 */
@Api(description = "店铺/仓库接口")
@RestController
@RequestMapping("/admin/shop")
public class ShopAdminController extends BaseController {

    @Autowired
    private ShopService shopService;

    @Autowired
    private EnterpriseService enterpriseService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysOfficeService sysOfficeService;


    @Autowired
    private SysEmployeeService sysEmployeeService;

    /**
     * 分页查询店铺/仓库
     *
     * @return
    */
    @ApiOperation("分页查询店铺/仓库")
    @GetMapping("/list")
    @ApiImplicitParams({@ApiImplicitParam(name = "name", value = "仓库名称", dataType = "String", paramType = "query") ,
            @ApiImplicitParam(name = "areaId", value = "城市", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "type", value = "类型{0:店铺,1:提货点,2:仓库}", dataType = "Integer", paramType = "query"),
            @ApiImplicitParam(name = "receiverId", value = "收货地址", dataType = "Long", paramType = "query"),
            @ApiImplicitParam(name = "supplierId", value = "供应商Id", dataType = "Long", paramType = "query")
    })
    public CommResult<Shop> list(String name, Long areaId,Integer type,Long receiverId, Pageable pageable, Long supplierId) {
        Map<String, Object> params = new HashMap<String, Object>();
        params = buildSortField(params, pageable);
        if (StringUtils.isNotEmpty(name)){
            params.put("name", name);
        }

        if (areaId!=null){
            AreaUtils.encodeMap(areaId,params);
        }

        Enterprise enterprise = enterpriseService.getCurrent();
        if (enterprise!=null) {
            params.put("enterpriseId", enterprise.getId());
        } else {
            return CommResult.error("没有开通企业");
        }


        //非管理员都启用数据权限
        SysUser sysUser = sysUserService.getCurrent();
        if (!sysUserService.isAdmin(sysUser)) {
            if (sysUser.getMchId().equals(enterprise.getMchId())) {
                params.put("shopScopeId", sysUser.getId());
            }
        }


        if (type!=null) {
            params.put("type",type);
        }

        params.put("deleted",false);

        if (supplierId!=null) {
            params.put("supplierId",supplierId);
        }

        Page<Object> startPage = PageHelper.startPage(pageable.getPageNum(), pageable.getPageSize());
        List<Shop> list = shopService.selectList(params);
        PageResult<Shop> pageResult = new PageResult<Shop>(list, startPage.getTotal(), pageable);
        return CommResult.success(pageResult);
    }

    /**
     * 查询单条店铺/仓库
     *
     * @return
    */
    @ApiOperation("查询单条店铺/仓库")
    @GetMapping("/find/{id}")
    public CommResult<Shop> find(@PathVariable String id) {
        Shop result = shopService.findById(id);

        Map<String,Object> data = new HashMap<>();
        data.put("shop",result);

        if (result.getOfficeId()!=null) {
            SysOffice sysOffice = sysOfficeService.selectByPrimaryKey(result.getOfficeId());
            if (sysOffice!=null) {
                data.put("officeName", sysOffice.getName());
            }
        }

        if (result.getManagerId()!=null) {
            SysEmployee sysEmployee = sysEmployeeService.selectByPrimaryKey(result.getManagerId());
            if (sysEmployee!=null) {
                data.put("managerName", sysEmployee.getName());
            }
        }

        return CommResult.success(data);

    }

    /**
     * 保存店铺/仓库
     *
     * @param shop
     * @return
     */
    @ApiOperation("保存店铺/仓库")
    @PostMapping("/save")
    public CommResult<Shop> save(@RequestBody Shop shop) {
        Enterprise enterprise = enterpriseService.getCurrent();
        shop.setEnterpriseId(enterprise.getId());
        shop.setDeleted(false);
        if (shop.getManagerId()!=null && shop.getManagerId()!="") {
            SysEmployee sysEmployee = sysEmployeeService.selectByPrimaryKey(shop.getManagerId());
            shop.setMemberId(sysEmployee.getMemberId());
        }
        int affectCount = shopService.insertUseGeneratedKeys(shop);
        if (affectCount <= 0) {
            return CommResult.error();
        }
        Shop result = shopService.findById(shop.getId());
        return CommResult.success(result);

    }


    /**
     * 批量删除店铺/仓库
     *
     * @param ids
     * @return
     */
    @Log(desc = "批量删除店铺/仓库", type = Log.LOG_TYPE.DEL)
    @ApiOperation("批量删除店铺/仓库,ids用逗号拼接")
    @PostMapping("/del/{ids}")
    public CommResult<Shop> del(@PathVariable String ids) {

        shopService.deleteByIds(ids.split(","));
        return CommResult.success();
    }

    /**
     * 更新店铺/仓库
     *
     * @param shop
     * @return
     */
    @Log(desc = "更新店铺/仓库", type = Log.LOG_TYPE.UPDATE)
    @ApiOperation("更新店铺/仓库")
    @PostMapping("/update")
    public CommResult<Shop> update(@RequestBody Shop shop) {
        if (shop.getManagerId()!=null) {
            SysEmployee sysEmployee = sysEmployeeService.selectByPrimaryKey(shop.getManagerId());
            shop.setMemberId(sysEmployee.getMemberId());
        }
        int affectCount = shopService.updateByPrimaryKeySelective(shop);
        if (affectCount <= 0){
            return CommResult.error();
        }
        Shop result = shopService.findById(shop.getId());
        return CommResult.success(result);
    }

}
